const Koa = require('koa')
const Router = require('koa-router')
const { koaBody } = require('koa-body')
const app = new Koa()
const router = new Router()

app.use(koaBody({
  multipart: true
}))

const PORT = 9090

router.prefix('/api/v1')

router.get('/ping', ctx => {
  ctx.body = "pong ~"
})

class User {
  constructor(name, age, salary) {
    this.name = name
    this.age = age
    this.salary = salary
  }

  getUserInfo () {
    return `User: name: ${this.name}, age: ${this.age}, salary: ${this.salary}!`
  }

}

const users = []

router.post('/user', ctx => {
  const { name, age, salary } = ctx.request.body
  const user = new User(name, age, salary)
  users.push(user)
  ctx.body = user
})

router.get('/users', ctx => {
  ctx.body = users
})

router.get('/getUserInfo', ctx => {
  const { name } = ctx.query
  const user = users.find(x => x.name === name)
  ctx.body = user || {}
})

app.use(router.routes())

app.listen(PORT, console.log(`Server is running at PORT: ${PORT} ...`))

